package com.ruoyi.scheduleTask

import cn.hutool.core.date.DateUtil
import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.ruoyi.app.common.NetUrlUploadOss
import com.ruoyi.back.domain.Template
import com.ruoyi.back.domain.UserMember
import com.ruoyi.back.domain.v3.VideoTemplateFaceService
import com.ruoyi.back.enums.NoticeTypeEnum
import com.ruoyi.back.service.TemplateService
import com.ruoyi.back.service.UserMemberMessageService
import com.ruoyi.back.service.UserMemberService
import com.ruoyi.socket.WebSocketServer
import com.ruoyi.util.addVideoTemplate
import com.ruoyi.util.asyncAddVideoTemplateResult
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.util.*


@Component
@EnableScheduling   // 1.开启定时任务
class AddTemplateFaceScheduleTask {

    private val log: Logger = LoggerFactory.getLogger(AddTemplateFaceScheduleTask::class.java)

    @Autowired
    private lateinit var templateService: TemplateService

    @Autowired
    private lateinit var videoTemplateFaceService: VideoTemplateFaceService

    @Autowired
    private lateinit var netUrlUploadOss: NetUrlUploadOss

    @Autowired
    private lateinit var userMemberService: UserMemberService

    @Autowired
    private lateinit var userMemberMessageService: UserMemberMessageService

    @Scheduled(fixedRate = 30 * 1000)
    fun scheduleTask() {
        templateService.list(
            KtQueryWrapper(Template::class.java)
                .eq(Template::requestStatus, 0)
        )
            .takeIf { it.isNotEmpty() }
            ?.run {
                forEach {

                    if (StrUtil.isNotBlank(it.requestId)) {
                        asyncAddVideoTemplateResult(it.requestId!!)?.let { videoTemplateFaces ->
                            log.info("${it.requestId} 处理成功!")
                            videoTemplateFaceService.saveBatch(videoTemplateFaces.map {
                                it.apply {
                                    templateFaceUrl = netUrlUploadOss.upload(templateFaceUrl!!)
                                }
                            })
                            templateService.updateById(it.apply {
                                requestStatus = 1
                                videoTemplateId = videoTemplateFaces[0].templateId
                            })
                        }
                    } else {
                        log.info("开始获取${it.id} 模板的 请求id ")
                        templateService.updateById(it.apply {
                            this.requestId = addVideoTemplate(content!!)
                            log.info("获取${it.id} 模板的 请求id结束 ->  ${this.requestId}")
                        })
                    }
                }
            }
    }

    /**
     * 自动判断会员是否到期
     */
    @Scheduled(cron = "0 0 10,14,16 * * ?")
    fun scheduleMember() {
        userMemberService.list(KtQueryWrapper(UserMember::class.java)
            .orderByDesc(UserMember::createTime))
            .takeIf { it.isNotEmpty() }
            ?.run {
                filter { DateUtil.betweenDay(Date(), it.endMemberDate, true) <= 7 }
                    .takeIf { it.isNotEmpty() }
                    ?.run {
                        forEach {
                            userMemberMessageService.sendUserMessage(NoticeTypeEnum.EXPIRE_MEMBER, it.createBy!!)
                            WebSocketServer.sendMessage(it.createBy!!)
                        }
                    }
            }
    }

}